{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "119e48b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai # 导入OpenAI，用于调用聊天模型\n",
    "import IPython # 导入IPython，用于展示聊天输出\n",
    "\n",
    "# 这里替换为你的 OpenAI API 密钥\n",
    "openai.api_key  = 'sk-xxxxx'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "736091b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 设置OpenAI API调用参数\n",
    "def set_open_params(\n",
    "    model=\"text-davinci-003\", # 模型\n",
    "    temperature=0.7, # 多样性\n",
    "    n = 1, # 返回结果的数量\n",
    "    max_tokens=256, # 生成结果的最大词数\n",
    "    top_p=1, # 随机抽样的阈值\n",
    "    frequency_penalty=0, # 调整生成的文本的常见度\n",
    "    presence_penalty=0, # 调整生成的文本中的新概念出现的频率\n",
    "):\n",
    "    openai_params = {}    \n",
    "    openai_params['model'] = model  # 使用的模型名称\n",
    "    openai_params['temperature'] = temperature  # 结果多样性的参数，数值越大结果越随机，反之越确定\n",
    "    openai_params['n'] = n  # 返回结果的数量\n",
    "    openai_params['max_tokens'] = max_tokens  # 生成结果的最大词数\n",
    "    openai_params['top_p'] = top_p  # 随机抽样的阈值，较小的值将使结果更加集中，较大的值将使结果更加分散\n",
    "    openai_params['frequency_penalty'] = frequency_penalty  # 调整生成的文本的常见度，较高的值将使模型更可能生成罕见的文本\n",
    "    openai_params['presence_penalty'] = presence_penalty  # 调整生成的文本中的新概念出现的频率，较高的值将使模型更可能引入新的概念\n",
    "    return openai_params\n",
    "\n",
    "params = set_open_params() # 设置参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0478fb51",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 从OpenAI API获取完成的文本\n",
    "def get_completion(params, prompt):\n",
    "    response = openai.Completion.create( # 调用Completion API\n",
    "        engine = params['model'], # 模型\n",
    "        prompt = prompt, # Prompt\n",
    "        temperature = params['temperature'], # 多样性\n",
    "        n = params['n'], # 返回结果的数量\n",
    "        max_tokens = params['max_tokens'], # 生成结果的最大词数\n",
    "        top_p = params['top_p'], # 随机抽样的阈值\n",
    "        frequency_penalty = params['frequency_penalty'], # 生成的文本的常见度\n",
    "        presence_penalty = params['presence_penalty'], # 生成的文本中的新概念出现的频率\n",
    "    )\n",
    "    return response # 接收模型的聊天返回结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bd6a5d16",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<OpenAIObject text_completion id=cmpl-7WLjmcdAsGsX1nLQnmIcWfmlYK351 at 0x19898757f10> JSON: {\n",
       "  \"choices\": [\n",
       "    {\n",
       "      \"finish_reason\": \"stop\",\n",
       "      \"index\": 0,\n",
       "      \"logprobs\": null,\n",
       "      \"text\": \" a natural satellite\\n\\nThe moon is a natural satellite of Earth, the only natural satellite of the planet in the Solar System. The Moon orbits Earth at an average distance of 384,400 km, and it has a diameter of 3,476 km. It has no atmosphere, and its gravity is about one-sixth of Earth's. The Moon has been a source of fascination for humans since ancient times, and it is the only celestial body that is visible to the naked eye from Earth.\"\n",
       "    }\n",
       "  ],\n",
       "  \"created\": 1687944410,\n",
       "  \"id\": \"cmpl-7WLjmcdAsGsX1nLQnmIcWfmlYK351\",\n",
       "  \"model\": \"text-davinci-003\",\n",
       "  \"object\": \"text_completion\",\n",
       "  \"usage\": {\n",
       "    \"completion_tokens\": 100,\n",
       "    \"prompt_tokens\": 3,\n",
       "    \"total_tokens\": 103\n",
       "  }\n",
       "}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 简单示例\n",
    "prompt = \"The moon is\" # 设置Prompt\n",
    "response = get_completion(params, prompt) # 调用API\n",
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "34f854e8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'openai.openai_object.OpenAIObject'>\n",
      " a natural satellite\n",
      "\n",
      "The moon is a natural satellite of Earth, the only natural satellite of the planet in the Solar System. The Moon orbits Earth at an average distance of 384,400 km, and it has a diameter of 3,476 km. It has no atmosphere, and its gravity is about one-sixth of Earth's. The Moon has been a source of fascination for humans since ancient times, and it is the only celestial body that is visible to the naked eye from Earth.\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       " a natural satellite\n",
       "\n",
       "The moon is a natural satellite of Earth, the only natural satellite of the planet in the Solar System. The Moon orbits Earth at an average distance of 384,400 km, and it has a diameter of 3,476 km. It has no atmosphere, and its gravity is about one-sixth of Earth's. The Moon has been a source of fascination for humans since ancient times, and it is the only celestial body that is visible to the naked eye from Earth."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import IPython\n",
    "print(type(response))\n",
    "print(response.choices[0].text)\n",
    "IPython.display.Markdown(response.choices[0].text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a35fdceb",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
